<?php

namespace Muyuxuanpay\threePay;

use Muyuxuanpay\tool\Mtool;

trait BaseTrait
{
    protected $config = [];//配置
    protected $resalut = [];
    public function __construct(array $config=[])
    {
        if(!empty($config)){
            $this->setConfig($config);
        }
    }

    /**
     * 获取结果
     * @return array|mixed
     */
    public function getResalut()
    {
        return $this->resalut;
    }

    /**
     * 获取配置
     * @return array|mixed
     */
    public function getConfig()
    {
        return $this->config;
    }

    /**
     * 设置配置
     * @param array $config
     * @return void
     * @throws \Exception
     */
    public function setConfig(array $config)
    {
        if(empty($config)){
            throw new \Exception('请设置支付配置');
        }
        if(empty($this->config)){
            $this->config = $config;
        }else{
            $this->config = Mtool::depth_array_merge($this->config,$config);
        }
    }

    /**
     * 获取客户端ip地址
     * @return mixed|string
     */
    public function getClientIp()
    {
        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
            // 如果客户端使用了代理，获取的IP会保存在HTTP_CLIENT_IP中
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            // 如果客户端使用了多级代理，获取的IP会保存在HTTP_X_FORWARDED_FOR中
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } else {
            // 否则，直接获取REMOTE_ADDR即可
            if(isset($_SERVER['REMOTE_ADDR'])){
                $ip = $_SERVER['REMOTE_ADDR'];
            }else{
                $ip = '127.0.0.1';
            }
        }
        return $ip;
    }

    /**
     * 验证配置是否完整
     * @return void
     * @throws \Exception
     */
    protected function verify()
    {
        if(!empty($this->must)){
            foreach ($this->must as $key=>$val){
                if(is_numeric($key)){
                    if(empty($this->config[$key])){
                        throw new \Exception("请设置{$key}参数");
                    }
                }else{
                    if(empty($this->config[$key])){
                        throw new \Exception("请设置{$val}参数");
                    }
                }
            }
        }
    }

    /**
     * 数据映射
     * @param array $data
     * @return array
     */
    protected function mapping(array $data=[])
    {
        if(empty($data)){
            return $data;
        }
        $nData = [];
        foreach ($data as $key=>$val){
            if(isset($this->dataMapping[$key])){
                $nData[$this->dataMapping[$key]] = $val;
            }else{
                $nData[$key] = $val;
            }
        }
        return $nData;
    }
}